﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Drawing;
using RooHui.Tool;
using RooHui.Application.CommonWebLogic;
using RooHui.Infrastructure.Entities.Entity;
using RooHui.Infrastructure.Entities.Enum;
using RooHui.Portal.Biz;

namespace RooHui.Portal.Web.Controllers
{
    [ErrorHandle]
    public class AccountController : Controller
    {
        #region Login
        //
        // GET: /Account/

        public ActionResult Login(string returnurl)
        {
            ViewBag.ReturnUrl = returnurl;
            return View();
        }

        [HttpPost]
        public ActionResult Login(string username, string password, string returnurl, string code)
        {
            username = username.ToLower();
            if (!String.IsNullOrEmpty(username))
            {
                ViewBag.Username = username;
                if (!String.IsNullOrEmpty(Request.Form["reset"]))
                {
                    if (String.IsNullOrEmpty(code) || !ValidateValidateCode(code))
                    {
                        ViewBag.Validation = "open";
                        ViewBag.Message = "验证码输入有误";
                        return View();
                    }
                }
                var member = MemberBiz.Login(username, password);
                if (member == null)
                {
                    ViewBag.Validation = "open";
                    ViewBag.Message = "您的密码有误，请重新输入";
                    return View();
                }
                if (!member.IsActive)
                {
                    return RedirectToAction("AuthCheck", new { u = EncodeByBase64.Encode(username) });
                }
                if (!String.IsNullOrEmpty(returnurl))
                {
                    return Redirect(returnurl);
                }
                return Redirect("/");
            }
            return View();
        }

        public ActionResult Logout()
        {
            System.Web.Security.FormsAuthentication.SignOut();
            return Redirect("/");
        }
        #endregion

        #region Register
        public ActionResult Register()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Register(string username, string password, string confirm, string validationCode)
        {
            username = username.ToLower();
            if (!ValidateValidateCode(validationCode))
            {
                ViewBag.Message = "验证码输入错误";
                return View();
            }
            if (password != confirm)
            {
                ViewBag.Message = "两次密码输入不一致";
                return View();
            }
            var user = new Member()
            {
                UserName = username,
                Email = username,
                Gender = Gender.Unknow,
                CreateTime = DateTime.Now,
                CreateType = CreateType.Normal,
                Password = password,
                IsActive = false,
                Status = ItemStatus.Enable,
                MemberType = MemberType.Invester,
                RegisterIP = HttpContext.Request.ServerVariables["REMOTE_ADDR"].ToString()
            };
            if (MemberBiz.Register(user) == null)
            {
                LogHelper.Write(CommonLogger.UserSystem, LogLevel.Error, String.Format("用户：{0}注册失败。注册数据为：{1}",
                   user.UserName, user.ToJson()));
                ViewBag.Message = "用户名重复，请重新输入";
                return View();
            }
            return RedirectToAction("registerpaymentaccount", new { u = EncodeByBase64.Encode(username) });
        }
        /// <summary>
        /// 验证验证码是否正确
        /// </summary>
        /// <returns></returns>
        private bool ValidateValidateCode(string code)
        {
            bool result;

            string token = Request.Params["token"];
            if (token == null)
            {
                result = false;
            }
            else
            {
                token = Cryptogram.CommonEncrypt(token);
                //过虑加密后出现的非法字符
                token = token.Replace("/", "");
                token = token.Replace("+", "");
                token = token.Replace("=", "");
                token = token.Substring(0, 4).ToString();
                token = token.ToLower();
                //过虑0为O,I和1
                token = token.Replace("0", "o");
                token = token.Replace("1", "i");
                string validStr = code.ToLower();
                //o,0转换，i,1转换
                validStr = validStr.Replace("0", "o");
                validStr = validStr.Replace("1", "i");
                if (validStr != token)
                    result = false;
                else
                    result = true;
            }
            return result;
        }
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <param name="t"></param>
        [HttpGet]
        public void validatetoken(string t)
        {
            const int width = 60, height = 25;
            Bitmap aBmp = new Bitmap(width, height);
            Graphics aGrph = Graphics.FromImage(aBmp);
            aGrph.FillRectangle(new SolidBrush(Color.FromArgb(68, 68, 68)), 0, 0, width, height);//255,153,0

            //string adPitch = ssolib.Cryptogram.CommonDecrypt(Request.QueryString["yyMM"].ToString());

            //为了解决浏览器后退，验证码不刷新的问题，对验证码的实现做了修改。
            string adPitch = Cryptogram.CommonEncrypt(t);

            adPitch = adPitch.Replace("/", "");
            adPitch = adPitch.Replace("+", "");
            adPitch = adPitch.Replace("=", "");

            adPitch = adPitch.Substring(0, 4);

            adPitch = adPitch.ToUpper();

            //过虑0为O,I和1
            adPitch = adPitch.Replace("0", "O");
            adPitch = adPitch.Replace("1", "I");
            new VerifyCodeImage().CreateImageOnPage(adPitch, System.Web.HttpContext.Current);

        }
        /// <summary>
        /// 如果验证用户名为不存在返回 true
        ///              否则返回 false
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public bool usernameonly(string username)
        {
            var exists = MemberBiz.UserNotExists(username);
            return exists;
        }

        public bool hasusername(string username)
        {
            return !usernameonly(username);
        }
        #endregion

        #region paymentAccount
        public ActionResult RegisterPaymentAccount(string u)
        {
            ViewBag.U = u;
            return View();
        }
        #endregion

        #region InfoAuth
        public ActionResult AuthCheck(string u)
        {
            string username = Tool.EncodeByBase64.Decode(u);
            MemberBiz.ReSendActiveMail(username);
            ViewBag.Member = new Member().Find(username);
            return View();
        }
        /// <summary>
        /// 重发认证邮件
        /// </summary>
        /// <param name="u"></param>
        /// <returns></returns>
        public int resendemail(string u)
        {
            if (!string.IsNullOrEmpty(u))
            {
                var member = MemberBiz.ReSendActiveMail(EncodeByBase64.Decode(u));
                if (member != null)
                {
                    return 1;
                }
            }
            return 0;
        }
        public ActionResult activation(string token)
        {
            if (MemberBiz.Activation(token) != null)
            {
                return RedirectToAction("RegisterSuccess");
            }
            return RedirectToAction("activationfail");
        }
        public ActionResult activationfail()
        {
            return View();
        }
        public ActionResult RegisterSuccess()
        {
            return View();
        }
        #endregion

        #region ForgetPassword
        public ActionResult Resetpassword()
        {
            return View();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="type">0：邮箱找回 1：手机短信找回</param>
        /// <param name="username"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult resetpassword(int type,string username)
        {
            if (String.IsNullOrEmpty(username))
            {
                ViewBag.Message = "输入有误，请重新输入";
                return View();
            }
            if (type == 0)
            {
                if (!MemberBiz.ResendForgotPasswordMail(username))
                {
                    ViewBag.Message = "该用户名不存在，请查证";
                    return View();
                }
                return RedirectToAction("CheckEmail");
            }
            else
            {
                return View();
            }
        }
        public ActionResult CheckEmail()
        {
            return View();
        }
        public ActionResult checkresetpassword(string token)
        {
            var member = MemberBiz.CheckToken(token);
            if (member != null)
            {
                ViewBag.User = member;
                return View();
            }
            else
            {
                return Redirect("/account/checkfail");
            }
        }
        public ActionResult CheckFail()
        {
            return View();
        }
        [HttpPost]
        public ActionResult setnewpassword(string u, string password)
        {
            string username = EncodeByBase64.Decode(u);
            MemberBiz.ChangePassword(username, password);
            return Redirect("/account/OperationDone");
        }
        public ActionResult OperationDone()
        {
            return View();
        }

        public string getmobilecode(string username, string mobile)
        {
            var member = new Member().Find(username);
            if(member == null || !member.HandPhoneCheck || member.HandPhone.Length != 11)
            {
                //用户不存在或未完成手机号认证
                return "9";
            }
            else if(member.HandPhone != mobile)
            {
                //用户名与手机号不匹配
                return "2";
            }
            SupportBiz.SendShortMessageCode(username, mobile, CheckCodeType.ResetPasswordShortMessageCode);  
            return "1";
        }
        public string checkmobilecode(string username, string mobile, string mobileCode)
        {
            var member = new Member().Find(username);
            if (member == null)
            {
                return "0";
            }
            else
            {
                if (member.HandPhoneCheck && member.HandPhone == mobile)
                { 
                    //验证手机验证码
                    if (SupportBiz.CheckShortMessageCode(username, mobileCode, CheckCodeType.ResetPasswordShortMessageCode))
                    {
                        return EncodeByBase64.Encode(username);
                    }
                }
            }
            return "0";
        }
        public ActionResult mobileCodeTypeResetPassword(string u, string password)
        {
            string username = EncodeByBase64.Decode(u);
            MemberBiz.ChangePassword(username, password);
            return RedirectToAction("OperationDone");
        }
        #endregion

        public string getAccountInfo(string u)
        {
            var member = new Member().Find(u);
            if (member != null)
            {
                //TODO:
                //调用第三方接口查询余额，后同步本地库
                //返回同步后的结果
                return new Account().Find(member.UserName).BalanceAmount.ToString();
            }
            return "0";
        }
    }
}
